package com.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.UserAction;
import com.bean.MessageBean;
import com.exception.DBException;
import com.exception.UserException;
import com.util.HandleInfo;
import com.util.Regex;
import com.util.StateInfo;

public class UserQueryServlet extends HttpServlet
{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		UserAction queryAction = new UserAction();
		String key = request.getParameter("limits");
		String value = request.getParameter("userkey");
		
		if(null==key || null == value)
		{
			HandleInfo.handle(request, response,  
					StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		if("".equals(key) || "".equals(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		if(!"userid".equals(key) && !"firstname".equals(key) && !"lastname".equals(key) && !"typename".equals(key))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		if ("userid".equals(key) && !Regex.checkUserID(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		// query users by firstname
		else if ("firstname".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		//query users by lastname
		else if ("lastname".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		//query users by typename
		else if ("typename".equals(key) && !Regex.checkName(value))
		{
			HandleInfo.handle(request, response, StateInfo.INNER_CONFIRM_FAIL);
			return;
		}
		
		MessageBean message = new MessageBean();
		message.setKey(key);
		message.setValue(value);
		try
		{
			queryAction.queryUsers(request, response,message);
		}
		catch (DBException e)
		{
			HandleInfo.handle(request, response, e.getMessage());
			return;
		}
		catch (UserException e)
		{
			HandleInfo.handle(request, response, e.getMessage());
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		doGet(request, response);
	}
	
}
